﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hi_Baidu;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;

namespace Hi_Baidu.Plugin
{
    /// <summary>
    ///     插件管理器
    /// </summary>
    public class PluginManager : Manager
    {
        /// <summary>
        ///     注册插件
        /// </summary>
        /// <param name="Plugin">插件</param>
        public void RegisterPlugin(IMetaData Plugin)
        {
            if (Plugin is IPlugin)
            {
                this.Collection.Add(Plugin);
            }
        }

        /// <summary>
        ///     根据默认路径得到可用插件
        /// </summary>
        public void FindPlugin()
        {
            FindPlugin(Directory.GetCurrentDirectory() + "../../Plugins/");
        }

        /// <summary>
        ///     根据指定文件路径得到可用插件
        /// </summary>
        /// <param name="Path">插件集合文件路径</param>
        public void FindPlugin(String Path)
        {
            this.Collection.Clear();
            String[] Directorys = Directory.GetDirectories(Path);
            foreach (String directory in Directorys)
            {
                String[] Files = Directory.GetFiles(directory);
                foreach (String fileinfo in Files)
                {
                    FileInfo file = new FileInfo(fileinfo);
                    if (file.Extension.ToLower() == ".dll" && file.Exists)
                    {
                        Assembly assembly = Assembly.LoadFile(file.FullName);
                        Type[] fileTypes = assembly.GetTypes();
                        foreach (Type type in fileTypes)
                        {
                            Type typeInterface = type.GetInterface("Hi_Baidu.Plugin.IPlugin", true);
                            if (typeInterface != null)
                            {
                                IPlugin instance = (IPlugin)Activator.CreateInstance(assembly.GetType(type.ToString()));
                                this.RegisterPlugin(instance);
                            }
                        }
                    }
                }
            }
        }
    }
}
